//
//  GetEggRewardViewController.m
//  jingjing2.0
//
//  Created by apple on 16/5/24.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "GetEggRewardViewController.h"
#import "ColorEggData.h"
#import "whoClickEggData.h"
#import "RewardTableViewCell.h"
#import "JoinTableViewCell.h"
@interface GetEggRewardViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSString *_remark;
    UIView *_bgView;
    UIView *_shareView;
    enum WXScene _scene;
}
@property(nonatomic,strong)ShareData *shareData;
@property(nonatomic,strong)NSMutableArray *eggArr;
@property(nonatomic,strong)NSMutableArray *joinArr;
@property(nonatomic,strong)UITableView *tableView;
@end

@implementation GetEggRewardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets=NO;
    _eggArr=[NSMutableArray array];
    _joinArr=[NSMutableArray array];
    self.view.backgroundColor=LIGHTGRAY;
    self.title=@"彩蛋详情";
    [self setUpTableView];
    [self setUpHeadImageAndBtnImage];
    [self setUpShareView];
}
#pragma mark--分享视图
-(void)setUpShareView
{
    _bgView=[[UIView alloc]initWithFrame:self.view.frame];
    _bgView.backgroundColor=[UIColor blackColor];
    _bgView.alpha=0.7;
    _bgView.hidden=YES;
    [self.view addSubview:_bgView];
    
    _shareView=[[UIView alloc]initWithFrame:CGRectMake(0, kHeight-180, kWidth, 180)];
    _shareView.backgroundColor=[UIColor whiteColor];
    _shareView.hidden=YES;
    [self.view addSubview:_shareView];
    
    UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(10, 10, 25, 25)];
    [btn setBackgroundImage:[UIImage imageNamed:@"close_view"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(shareViewHide) forControlEvents:UIControlEventTouchUpInside];
    [_shareView addSubview:btn];
    
    UILabel *title=[[UILabel alloc]initWithFrame:CGRectMake(btn.frame.origin.x+25+5, 10, kWidth-20-25-5, 30)];
    title.text=@"分享彩蛋链接";
    title.textAlignment=NSTextAlignmentCenter;
    title.textColor=[UIColor darkGrayColor];
    [_shareView addSubview:title];
    
    UIView *line=[[UIView alloc]initWithFrame:CGRectMake(0,50, kWidth, 1)];
    line.backgroundColor=[UIColor lightGrayColor];
    [_shareView addSubview:line];
    
    for (int i=0; i<2; i++) {
        UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(i*(50+50)+20, line.frame.origin.y+1+20 , 50, 50)];
        if (i==0) {
             [btn setBackgroundImage:[UIImage imageNamed:@"send_weixin"] forState:UIControlStateNormal];
        }else
        {
            [btn setBackgroundImage:[UIImage imageNamed:@"wxpyq_shar"] forState:UIControlStateNormal];
        }
        btn.tag=(i+1)*100;
        [btn addTarget:self action:@selector(share:) forControlEvents:UIControlEventTouchUpInside];
        [_shareView addSubview:btn];
    }
    for (int i=0; i<2; i++) {
        UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake(i*(80+20)+20, line.frame.origin.y+1+20+50+10, 80, 50)];
        lbl.textColor=[UIColor darkGrayColor];
        if (i==0) {
            lbl.text=@"微信好友";
        }else
        {
            lbl.text=@"朋友圈";
        }
        [_shareView addSubview:lbl];
    }

    
}
-(void)share:(UIButton *)btn
{
    _bgView.hidden=YES;
    _shareView.hidden=YES;
    [self getShareMassege];
    if (btn.tag==100) {
        _scene=WXSceneSession;
    }else
    {
        _scene=WXSceneTimeline;
    }
    [self shareData];
}
-(void)share
{
    WXWebpageObject *wxwebobj=[[WXWebpageObject alloc]init];
    wxwebobj.webpageUrl= _shareData.ShareUrl;
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = _shareData.ShareTitle;
    message.description=_shareData.ShareDes;
    NSURL *_url = [NSURL URLWithString: _shareData.ShareImg];// 获取的图片地址
    [message setThumbImage:[UIImage imageWithData: [NSData dataWithContentsOfURL:_url]]];
    message.mediaObject=wxwebobj;
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    req.message = message;
    req.scene = _scene;
    [WXApi sendReq:req];

}
-(void)shareViewHide
{
    _bgView.hidden=YES;
    _shareView.hidden=YES;
}
#pragma mark--表头视图
-(void)setUpHeadImageAndBtnImage
{
    UIImageView *image=[[UIImageView alloc]init];
    image.bounds=CGRectMake(0, 0, 60, 60);
    image.center=CGPointMake(self.view.center.x, 104);
    image.image=[UIImage imageNamed:@"eggTop_icon"];
    [self.view addSubview:image];
    
    UIImageView *lineImage=[[UIImageView alloc]init];
    lineImage.frame=CGRectMake(70, image.frame.origin.y+55, kWidth-140, 40);
    lineImage.image=[UIImage imageNamed:@"egg_suc"];
    [self.view addSubview:lineImage];
    
    UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(10, kHeight-120, kWidth-20, 40)];
    [btn setTitle:@"邀请好友一起砸" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.layer.cornerRadius=4;
    btn.clipsToBounds=YES;
    [btn addTarget:self action:@selector(shareWithFriend) forControlEvents:UIControlEventTouchUpInside];
    btn.backgroundColor=BLUECOLOR;
    [self.view addSubview:btn];
    
    UIImageView *logo=[[UIImageView alloc]init];
    logo.frame=CGRectMake(120, kHeight-40-20, kWidth-240, 20);
    logo.image=[UIImage imageNamed:@"logo_gay"];
    [self.view addSubview:logo];
}
-(void)shareWithFriend
{
    _bgView.hidden=NO;
    _shareView.hidden=NO;
}
#pragma mark--表
-(void)setUpTableView
{
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(10, 160, kWidth-20, kHeight-160-130) style:UITableViewStylePlain];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.rowHeight=80;
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [_tableView registerNib:[UINib nibWithNibName:@"RewardTableViewCell" bundle:nil] forCellReuseIdentifier:@"reward"];
    [_tableView registerNib:[UINib nibWithNibName:@"JoinTableViewCell" bundle:nil] forCellReuseIdentifier:@"join"];
    [self.view addSubview:_tableView];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==1) {
        return 40;
    }
    return 0;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return _eggArr.count;
    }
    return _joinArr.count;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section==1) {
        return _remark;
    }
    return nil;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section==1) {
        UILabel *lbl=[[UILabel alloc]init];
        lbl.frame=CGRectMake(10, 0, kWidth-40, 30);
        lbl.backgroundColor=[UIColor clearColor];
        NSString * htmlString = _remark;
        //html格式转文本
        NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
        lbl.attributedText = attrStr;
        
        return lbl;
    }
    return nil;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
         ColorEggData *egg=_eggArr[indexPath.row];
        RewardTableViewCell *reward=[_tableView dequeueReusableCellWithIdentifier:@"reward" forIndexPath:indexPath];
        reward.selectionStyle=UITableViewCellSelectionStyleNone;
        reward.delegate=self;
        //未领取
        if (egg.GetStatus==0)
        {
            [reward.getReward setTitle:@"去领取" forState:UIControlStateNormal];
            reward.getReward.layer.borderColor=BLUECOLOR.CGColor;
            reward.getReward.tag=egg.GetNoteID;
            reward.getReward.number=egg.PrizeType;
            reward.getReward.pageUrl=egg.PrizePageUrl;
            reward.getReward.title=egg.PrizeName;
            [reward.getReward setTitleColor:BLUECOLOR forState:UIControlStateNormal];
            reward.getReward.enabled=YES;
        }else
        {
          //已领取
          [reward.getReward setTitle:@"已领取" forState:UIControlStateNormal];
            reward.getReward.layer.borderColor=GRAYCOLOR.CGColor;
          [reward.getReward setTitleColor:GRAYCOLOR forState:UIControlStateNormal];
          reward.getReward.enabled=NO;
        }
        
        [reward.image sd_setImageWithURL:[NSURL URLWithString:egg.PrizeImage] placeholderImage:nil options:SDWebImageRetryFailed];
        reward.name.text=egg.PrizeName;
        return reward;
    }else
    {
        JoinTableViewCell *join=[_tableView dequeueReusableCellWithIdentifier:@"join" forIndexPath:indexPath];
        join.selectionStyle=UITableViewCellSelectionStyleNone;
        whoClickEggData *people=_joinArr[indexPath.row];
        [join.headImage sd_setImageWithURL:[NSURL URLWithString:people.HeadImg] placeholderImage:nil options:SDWebImageRetryFailed];
        join.name.text=people.NickName;
        join.rewardName.text=people.PrizeNames;
        join.time.text=people.GetTime;
        
        join.remark.text=people.Remark;
        return join;
    }
}
#pragma mark--获取数据
-(void)getData
{
    //http://192.168.1.107:3722/Activity/ColorEggRewardV2/{UserCode}/{EggID}/{Timestamp}/{Sign}
    [_joinArr removeAllObjects];
    [_eggArr removeAllObjects];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString *timeStamp=[GeneralTool gettimestamp];
    NSDictionary *dic=@{@"UserCode":GETUSERCODE,
                        @"EggID":_eggID,
                        @"Timestamp":timeStamp};
    NSString *sign=[GeneralTool GetSin:dic];
    NSString *urlString=[NSString stringWithFormat:@"Activity/ColorEggRewardV2/%@/%@/%@/%@",GETUSERCODE,_eggID,timeStamp,sign];
    [RequestTool requestDataWithType:@"get" andUrlString:urlString andParameters:nil andRequestFinished:^(id responses, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        if (error) {
            [MBProgressHUD showError:@"无法获取奖励详情，请稍后再次尝试"];
        }
        if ([responses[@"IsSuccess"]integerValue]==1) {
            NSDictionary *dic=responses[@"ReturnObject"];
            NSArray *rewardArr=dic[@"ColorEggRewardList"];
            _remark=dic[@"Remark"];
            [rewardArr enumerateObjectsUsingBlock:^(NSDictionary * obj, NSUInteger idx, BOOL * _Nonnull stop) {
                ColorEggData *egg=[[ColorEggData alloc]initWithDic:obj];
                [_eggArr addObject:egg];
            }];
            NSArray *joinArr=dic[@"JoinOpenEggsList"];
            [joinArr enumerateObjectsUsingBlock:^(NSDictionary * obj, NSUInteger idx, BOOL * _Nonnull stop) {
                whoClickEggData *people=[[whoClickEggData alloc]initWithDic:obj];
                [_joinArr addObject:people];
            }];
            [self.tableView reloadData];
        }
    }];
    
}
#pragma mark--获取要分享的内容
-(void)getShareMassege
{
    //http://192.168.1.107:3722/Common/PageInfo/{UserCode}/{PageType}/{ObjectID}/{Timestamp}/{Sign}
    NSString *timeStamp=[GeneralTool gettimestamp];
    NSDictionary *dic=@{@"UserCode":GETUSERCODE,
                        @"PageType":@"SHARE_URL_COLOREGG",
                        @"ObjectID":_eggID,
                        @"Timestamp":timeStamp};
    NSString *sign=[GeneralTool GetSin:dic];
    NSString *urlString=[NSString stringWithFormat:@"Common/PageInfo/%@/%@/%@/%@/%@",GETUSERCODE,@"SHARE_URL_COLOREGG",_eggID,timeStamp,sign];
    [RequestTool requestDataWithType:@"get" andUrlString:urlString andParameters:nil andRequestFinished:^(id responses, NSError *error) {
        if (error) {
            [MBProgressHUD showError:@"无法获取分享内容，请稍后再试"];
        }
        if([responses[@"IsSuccess"]integerValue]==1)
        {
            _shareData=[[ShareData alloc]initWithDic:responses[@"ReturnObject"]];
        }else
        {
            [MBProgressHUD showError:responses[@"ReturnString"]];
        }
        
    }];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [GeneralTool hideTabBar];
    [self getData];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [GeneralTool showTabBar];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
